<?php

/**
 * Project: Espolon
 * Licence: BSD License
 * Link: http://espolon.org/
 * Copyright: Nicolas de Bari Embriz Garcia Rojas <nbari at espolon dot org>
 * Author: Nicolas de Bari Embriz Garcia Rojas <nbari at espolon dot org>
 * Version: Beta
 */

if (!defined('SITE_ROOT')) exit('No direct script access allowed');

// Quote variable to make safe
// http://php.net/mysql_real_escape_string
function quote_smart($value)
{
  // Stripslashes
  if (get_magic_quotes_gpc()) {
    $value = stripslashes($value);
  }
  // Quote if not integer
  if (!is_numeric($value)) {
    $value = "'" . mysql_escape_string($value) . "'";
  }
  return $value;
}

function check_rid($rid) {
  if (empty($rid) OR !(int)$rid ) { sign_out(); }
}

function sign_out() {
  $_SESSION = array();
  session_destroy();
  $cookiesSet = array_keys($_COOKIE);
  for ($x=0;$x<count($cookiesSet);$x++) setcookie($cookiesSet[$x],"",mktime(12,0,0,1, 1, 1990), '/');
  header('Location: /');
  exit;
}

/**
 *  SESSIONS
 */
function sess_start() {
  if(!session_id()) session_start();
 # if((rand()%10) == 0)  adodb_session_regenerate_id();   // problems with this
}

function sess_set ($name, $value) {
  $_SESSION[$name] = $value;
}

function sess_get ($name) {
  if (isset($_SESSION[$name])) {
    return $_SESSION[$name];
  } else {
    return false;
  }
}

function sess_unset ($name) {
  $_SESSION[$name] = null;
  unset($_SESSION[$name]);
}

function sess_destroy () {
  $_SESSION = array();
  session_destroy();
}

/**
 * form
 * usage: if(postvars('form_name','form_message')) [...]
 */
function postvars() {
   foreach(func_get_args() as $var) {
       if(!isset($_POST[$var]) || $_POST[$var] === '') return false;
   }
   return true;
}

/**
 * ADODB functions
 */

function debug_sql($sql) {
  global $debug;
  $debug .= $sql;
}

function NotifyFn($expireref, $sesskey) {
  session_regenerate_id();
 /*
  global $ADODB_SESS_CONN; # the session connection object
  $user = $ADODB_SESS_CONN->qstr($expireref);
  $rs = $ADODB_SESS_CONN->GetRow("SELECT * FROM users WHERE uid=$user");
  print_r($rs);
  */
}

function cacheflush($db) {
  $exec_cache = realpath(SITE_ROOT.'../exec/adodbcache/');
	$command = ("find $exec_cache -name 'adodb_*.cache' -exec rm -f {} \;");
  exec($command);
  $db->CacheFlush();
}

function RemoveExtension($strName) {
  $ext = strrchr($strName, '.');
  if($ext !== false) {
    $strName = substr($strName, 0, -strlen($ext));
  }
  return $strName;
}

function rmdirr ($dir) {
	if (is_dir ($dir)) {
		if (cleardir ($dir)) {
			return rmdir ($dir);
		}
		return false;
	}
	return unlink ($dir);
}

function cleardir($dir) {
	if (!($dir = dir ($dir))) {
		return false;
	}
	while (false !== $item = $dir->read()) {
		if ($item != '.' && $item != '..' && !rmdirr ($dir->path . DIRECTORY_SEPARATOR . $item)) {
			$dir->close();
			return false;
		}
	}
	$dir->close();
	return true;
}

function array_search_dups($array) {
   $dup_array = $array;
   $dup_array = array_unique($dup_array);
   if(count($dup_array) != count($array))
   {
       return true;
   }
   else
   {
       return false;
   }
}

function format_filesize($bytes, $decimals = 1) {
  $units = array(
    '1152921504606846976' => 'EB', /* Exa Byte  10^18 */
    '1125899906842624'    => 'PB', /* Peta Byte 10^15 */
    '1099511627776'       => 'TB',
    '1073741824'          => 'GB',
    '1048576'             => 'MB',
    '1024'                => 'KB'
  );

  if($bytes <= 1024)
    return $bytes . " Bytes";

  foreach($units as $base => $title)
    if(floor($bytes / $base) != 0)
      return number_format($bytes / $base, $decimals, ".", "'") . ' ' . $title;
}

function csv_string_to_array($str) {
   $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
   $results=preg_split($expr,trim($str));
   return preg_replace("/^\"(.*)\"$/","$1",$results);
}

function preg_array($pattern, $array) {
  $match = 0;
  foreach ($array as $key => $value) {
    if (!preg_match($pattern, $value)) {
      $match = 1;
      break;
    }
  }
  return ($match == 0) ? true : false;
}

function mb_unserialize($serial_str) {
  $out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str);
  return unserialize($out);
}

function is_number($number) {
  $text = (string)$number;
  $textlen = strlen($text);
  if ($textlen==0) return 0;
  for ($i=0;$i < $textlen;$i++)
  { $ch = ord($text{$i});
     if (($ch<48) || ($ch>57)) return 0;
  }
  return 1;
}

function indent($string,$chars=4,$char=" ") {
  return preg_replace('!^!m',str_repeat($char,$chars),$string);
}


?>